import Vue from "vue"
import axios from "axios";
import {MessageBox} from "element-ui";
import router from "router"

let http = axios.create({
    timeout: 5000,
    baseURL: process.env.NODE_ENV === "production" ? "/" : "/api",
})
const TOKEN_KEY = "BLOG_TOKEN"

http.interceptors.request.use(config => {
    config.headers.common['hjl'] = '666'
    const token = window.localStorage.getItem(TOKEN_KEY);
//     这里可以设置URL白名单
    if (token) {
        config.headers.common['Authorization'] = 'Bearer ' + token;
    }
    return config
}, error => {
    return Promise.reject(error) // 返回接口返回的错误信息
})


http.interceptors.response.use(
    response => {
        let {data, config} = response;
        if (data.code === 0) {
            if (config.url === "/user/login") {
                localStorage.setItem(TOKEN_KEY, data.data.token)
            }
        } else if (data.code === -666) {
//       console.log("拦截器知道token过期了")
            MessageBox.confirm("登陆过期了", "过期", {
                confirmButtonText: "登录",
                showCancelButton: false,
                type: "warning"
            }).then(() => {
                localStorage.removeItem(TOKEN_KEY)
                router.push({path: "/login"})
            })
        }
        return data
    },
    //接口错误状态处理，也就是说无响应时的处理
    error => {
        return Promise.reject(error) // 返回接口返回的错误信息
    })


Vue.prototype.$http = http
export {TOKEN_KEY, http}


